import React from 'react';
import {browserHistory} from 'react-router';
import { InputNumber, Radio, Input, Checkbox, Row, Col, Button, Icon, message, Modal, Tooltip, Popconfirm, Card, BackTop, notification } from 'antd';
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
const TextArea = Input.TextArea;
import * as actions from './../../actions/frontEnd/homeAction';
import Sidebar from './../../pages/frontEnd/Sidebar';

export default class productDetail extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        productDetial: { product:{} },
        selectNum: 1,
        selectColors: "",
        selectSizes: "",

        isAnonymity: false,
        textContent: "",
        isFollow: false,
        isDisable: true
      }
    }
    componentDidMount(){
      actions.findProductDetial(this, this.props.routeParams.id);
      window.onresize = function () {
        var height = document.body.clientHeight - 30;
        var marginTop = (window.innerHeight - 210) + "px";

        $("#divProductDetail").css({"height": height});
        $(".divFeekbook").css({"margin-top": marginTop});
      }
      window.onresize();

      //商品图片，放大功能
      var obj = new mag('.divUserHead', '.bigshow','.smallshow','.mask','.bigitem');
      obj.init();
    }
    onImgLoad(e){
      $(e.currentTarget).css("backgroundImage", "none");
    }
    cloneObj(obj){
        var str, newobj = obj.constructor === Array ? [] : {};
        if(typeof obj !== 'object'){
            return;
        } else if(window.JSON){
            str = JSON.stringify(obj), //序列化对象
            newobj = JSON.parse(str); //还原
        } else {
            for(var i in obj){
                newobj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
            }
        }
        return newobj;
    }
    addToCart(){
      var paramData = {
        pId: this.state.productDetial.product.id, //商品的数据库id
        productName: this.state.productDetial.product.productName, //商品名
        price: this.state.productDetial.product.price, //商品当前价格
        discountPrice: this.state.productDetial.product.discountPrice, //商品打折价格
        desc: this.state.productDetial.product.title, //商品描述++++++++++
        type: this.state.productDetial.product.type, //类型
        title: this.state.productDetial.product.title, //商品标题
        size: this.state.selectSizes, //商品型号  这个是单选的哈，不像商品那个类里面是个集合
        productColor: this.state.selectColors, //商品颜色  也是单选的
        productPic: this.state.productDetial.product.productPic,  //商品图片
        ingredients: this.state.productDetial.product.ingredients, //商品成分
        brandName: this.state.productDetial.product.brandName, //品牌
        placeOfProduction: this.state.productDetial.product.placeOfProduction, //商品产地
        qualityGuaranteePeriod: this.state.productDetial.product.qualityGuaranteePeriod.toString(), //保质期
        reminder: this.state.productDetial.product.reminder, //提醒
        purchaseNum: this.state.selectNum //商品数量
      }

      actions.addOrEditShoppingCart(this, paramData, 'add');
    }
    onSelectNum(val){
      this.setState({selectNum: val});
    }
    onSelectSizes(val){
      this.setState({selectSizes: val.target.value});
    }
    onSelectColors(val){
      this.setState({selectColors: val.target.value});
    }
    onIsAnonymity(val){
      this.setState({isAnonymity: val.target.checked});
    }
    onChangeText(val){
      this.setState({textContent: val.target.value});
    }
    btnSubmitComment(){
      if(this.state.textContent != ""){
        var paramData = {
          content: this.state.textContent,
          status: "active",
          anonymity: this.state.isAnonymity
        }
        actions.addComment(this,this.state.productDetial.product.id, paramData);
      }else {
        Modal.warning({
          title: '提示：',
          content: '评论内容，不能为空。'
        });
      }
    }
    weatherFollow(){
      if(this.state.productDetial.relatedProducts != undefined){
        if(this.state.isFollow == false){
          actions.weatherFollow(this, this.state.productDetial.product.id, "follow");
        }else {
          actions.weatherFollow(this, this.state.productDetial.product.id, "unFollow");
        }
      }
    }
    render() {
      var imgCoverPicture = null; var sizes = null; var productColors = null;  var imageElement = null; var commentElement = ""; var commentNum = ""; var relatedProducts = null;
      var imgBigShow = null; var btnFollow = null;

      if(this.state.productDetial.product != null){
        imgCoverPicture = <div className="divUserHead" style={{marginRight: '32px', cursor: 'move', position: 'relative'}}>
            {this.state.productDetial.product.productPic ? <img src={"http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + this.state.productDetial.product.productPic} onLoad={this.onImgLoad.bind(this)} className="imgProduct"/> : <img src="/src/styles/images/listDefault_Large.png" className="imgProduct"/>}
            <div className="mask"></div>
        </div>
        imgBigShow = <div className="bigshow">
            <div className="bigitem">
                {this.state.productDetial.product.productPic ? <img src={"http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + this.state.productDetial.product.productPic} onLoad={this.onImgLoad.bind(this)} className="imgProduct"/> : <img src="/src/styles/images/listDefault_Large.png" className="imgProduct"/>}
            </div>
        </div>

        if(this.state.productDetial.product.sizes != undefined){
          sizes = <RadioGroup defaultValue={this.state.productDetial.product.sizes[0]} onChange={this.onSelectSizes.bind(this)}>
            {
              this.state.productDetial.product.sizes.map((item, index)=>{
                return (<RadioButton key={index} value={item}>{item}</RadioButton>)
              })
            }
          </RadioGroup>
        }

        if(this.state.productDetial.product.productColors != undefined){
          productColors = <RadioGroup defaultValue={this.state.productDetial.product.productColors[0]} onChange={this.onSelectColors.bind(this)}>
            {
              this.state.productDetial.product.productColors.map((item, index)=>{
                return (<RadioButton key={index} value={item}>{item}</RadioButton>)
              })
            }
          </RadioGroup>
        }
      }else {
        imgCoverPicture = <div className="divUserHead" style={{marginRight: '32px'}}>
          <img className="imgCoverPicture" src="/src/styles/images/default.png"/>
        </div>
      }
      if(this.state.productDetial != null && this.state.productDetial.imageTextList != undefined){
          imageElement = <div id="divImageText" style={{paddingTop: '10px'}}>
                {
                    this.state.productDetial.imageTextList.map((item, index)=>{
                        return(<div key={index} className="divSubItem" style={{marginBottom: '10px'}}>
                            <img src={((item.pic)?"http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + item.pic:"")} style={{marginLeft: 'auto', marginRight: 'auto', display: ((item.pic ==  undefined)?'none':'block')}}/>
                            <div dangerouslySetInnerHTML={{__html: item.content}} style={{wordWrap: 'break-word', marginTop: '20px', marginBottom: '20px'}}/>
                        </div>)
                    })
                }
            </div>
      }
      //商品关联（遍历）
      var relatedProducts = <div className="divFooter"></div>;
      if(this.state.productDetial != null && this.state.productDetial.relatedProducts != undefined){
          var relatedContainer = null;
          var relatedItem = this.state.productDetial.relatedProducts.map((item, index)=>{
              var imgCoverPicture = null;
              if(item.productPic != undefined){
                  imgCoverPicture = <div className="divUserHead" style={{marginLeft: '-5px'}}>
                    <img className="imgCoverPicture" src={"http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + item.productPic} onLoad={this.onImgLoad.bind(this)}/>
                  </div>
              }else{
                  imgCoverPicture = <div className="divUserHead" style={{marginLeft: '-5px'}}>
                    <img className="imgCoverPicture" src="/src/styles/images/default.png"/>
                  </div>
              }
              // onClick={this.gotoSelectProduct.bind(this, item.id)}
              return(<div key={index} className="divSubItem">
                  <a href={"/productDetail/" + item.id}>
                    <Card className="divItemLineMini" style={{width: '316px'}}>
                        {imgCoverPicture}
                        <div className="userInfo" style={{ marginTop: '291px', marginLeft: '-305px'}}>
                            <div className="divArticleTitle1" style={{width: '287px'}} title={((item.productName == undefined)?"":item.productName)}>
                                <span>{'商品名：' + ((item.productName == undefined)?"":item.productName) + ((item.brandName == undefined)?"":"（" + item.brandName + "）")}</span>
                            </div>
                            <div className="divArticleContent2" style={{width: '287px'}} title={((item.reminder == undefined)?"":item.reminder)}>
                                <span>{'温馨提示：' + ((item.reminder == undefined)?"":item.reminder)}</span>
                            </div>
                            <div className="pOverview" style={{width: '293px'}}>
                                <span style={{color: '#fff'}}>
                                  <Icon type="eye" className="iconEye" title="浏览"/>{item.browseNumbers}
                                  <Icon type="message" className="iconEye" title="评论"/>{item.commentIds.length}
                                </span>
                            </div>
                            <div className="divContent" style={{width: '309px'}}>
                                <span>{'创建：' + ((item.commitTime == undefined)?"":new Date(item.commitTime).Format("yyyy-MM-dd"))}</span>
                                {/*<span>{((item.updateTime == undefined)?"":'，修改：' + new Date(item.updateTime).Format("yyyy-MM-dd"))}</span>*/}
                            </div>
                        </div>
                    </Card>
                  </a>
              </div>)
          })
          if(this.state.productDetial.relatedProducts.length <= 0){
            relatedContainer = <div className="divEmptComment">对不起，没有相关产品</div>
          }else {
            relatedContainer = <div className="divFlexListMini divRelatedItem" style={{marginBottom: '30px'}}>
              {relatedItem}
            </div>
          }
          relatedProducts = <div id="divImageText" style={{paddingTop: '10px'}}>
              <div className="divRelatedProducts">
                <div className="divRelatedProductsTitle">相关商品{"（" + this.state.productDetial.relatedProducts.length + "）"}</div>
              </div>
              {relatedContainer}
          </div>
      }
      if(this.state.productDetial.comments != undefined){
        if(this.state.productDetial.comments.length >= 1){
          commentNum = "（" + this.state.productDetial.comments.length + "）";
          commentElement = this.state.productDetial.comments.map((item, index) => {
              var commentorName = "";
              if(item.anonymity == true){
                commentorName = item.id.substr(0, 8)+"!@#$";
              }else {
                commentorName = item.commentorName;
              }
              item.commentDate = new Date(item.commentDate).Format("yyyy-MM-dd hh:mm");
              return (
                <div className="divItem" key={index}>
                  <div className="divInfo">
                    <img src={(item.avatarUrl)?"http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + item.avatarUrl:""} className="imgAvatar"/>
                    <div>{commentorName}</div>
                  </div>
                  <div className="divContent">{item.content}</div>
                  <div className="divCommentDate">{item.commentDate}</div>
                </div>
              );
          })
        }else {
          commentNum = "（0）";
          commentElement = <div className="divEmptComment">对不起，没有相关评论</div>
        }
      }
      if(sessionStorage.getItem("username") == null){
        btnFollow = <Tooltip placement="bottomLeft" title="请登录，才能关注。">
          <Button icon={(this.state.isFollow)?"star":"star-o"} disabled={this.state.isDisable}  onClick={this.weatherFollow.bind(this)}>关注</Button>
        </Tooltip>
      }else {
        btnFollow = <Button icon={(this.state.isFollow)?"star":"star-o"} disabled={this.state.isDisable}  onClick={this.weatherFollow.bind(this)}>关注</Button>
      }

      return (
        <div id="divProductDetail">
          <div className="divDetail" style={{width: '1070px', paddingTop: '10px'}}>
              {imgCoverPicture}
              {imgBigShow}

              <div className="productInfo">
                  <div className="divProductTitle" title={((this.state.productDetial.product.productName == undefined)?"":this.state.productDetial.product.productName) + '(' + ((this.state.productDetial.product.brandName == undefined)?"":this.state.productDetial.product.brandName) + ")"}>
                      <span>{((this.state.productDetial.product.productName == undefined)?"":this.state.productDetial.product.productName)}{'(' + ((this.state.productDetial.product.brandName == undefined)?"":this.state.productDetial.product.brandName)+")"}</span>
                      <div className="divProductSubTitle" title={((this.state.productDetial.product.title == undefined)?"":this.state.productDetial.product.title)}>{((this.state.productDetial.product.title == undefined)?"":this.state.productDetial.product.title)}</div>
                  </div>
                  <div className="divProductPrice">
                      <span className="spanPriceSymbol">Rm</span>
                      <span className="spanPrice">{((this.state.productDetial.product.discountPrice == undefined)?"":this.state.productDetial.product.discountPrice)}</span>
                      <span className="spanDiscountPrice">{'Rm ' + ((this.state.productDetial.product.price == undefined)?"":this.state.productDetial.product.price)}</span>

                      <span className="spanBrowseAndStock" style={{color: '#9a9a9a'}}>
                        <span title="浏览次数"><Icon type="eye" className="iconEye"/>{this.state.productDetial.product.browseNumbers}</span>
                        <span title="库存"><Icon type="shop" className="iconLike"/>{this.state.productDetial.product.stock}</span>
                      </span>
                  </div>
                  <div className="divProductContent" title={((this.state.productDetial.product.placeOfProduction == undefined)?"":this.state.productDetial.product.placeOfProduction)}>
                      <span className="spanPlaceOfProduction">产地:</span>
                      <span className="spanPlaceOfProductionContent">{((this.state.productDetial.product.placeOfProduction == undefined)?"":this.state.productDetial.product.placeOfProduction)}</span>
                  </div>
                  <div className="divSizes">
                    <div className="divText">尺寸:</div>
                    {sizes}
                  </div>
                  <div className="divProductColors">
                    <div className="divText">产品颜色:</div>
                    {productColors}
                  </div>
                  <div className="divOperations" style={{justifyContent: 'initial'}}>
                    <div className="divSelectNum">
                      数量： <InputNumber min={1} defaultValue={1} onChange={this.onSelectNum.bind(this)} />
                    </div>
                    <Button icon="shopping-cart" style={{marginRight: '247px'}} type="primary" onClick={this.addToCart.bind(this)}>加入购物车</Button>
                    <img src="/src/styles/images/shoppingCart.png" className="imgShoppingAnimation" />
                    {btnFollow}
                  </div>
              </div>
              <img src="/src/styles/images/Banners.png" style={{width: '1070px', marginTop: '15px'}} />
              <div className="divIngredients" title={((this.state.productDetial.product.reminder == undefined)?"":this.state.productDetial.product.reminder)}>
                  <div className="divIngredientsTitle">
                    <hr />
                    <div className="divTitle">成分描述</div>
                  </div>
                  <div className="divIngredientsContent">{((this.state.productDetial.product.ingredients == undefined)?"":this.state.productDetial.product.ingredients)}</div>
              </div>
              <div className="divReminder" title={((this.state.productDetial.product.reminder == undefined)?"":this.state.productDetial.product.reminder)}>
                  <div className="divReminderTitle">
                    <hr />
                    <div className="divTitle">温馨提示</div>
                  </div>
                  <div className="divReminderContent">{((this.state.productDetial.product.reminder == undefined)?"":this.state.productDetial.product.reminder)}</div>
              </div>
              {imageElement}
              {relatedProducts}

              <div>
                <div className="divRelatedProducts" style={{borderBottom: '1px solid #1890ff'}}>
                  <div className="divRelatedProductsTitle" style={{backgroundColor: '#1890ff'}}>商品评论{commentNum}</div>
                </div>
                {commentElement}
                <div>
                  <TextArea rows={4} placeholder="请输入评论..." onChange={this.onChangeText.bind(this)} value={this.state.textContent} style={{resize: 'none'}}/>
                  <div style={{textAlign: 'right', margin: '14px', marginRight: '0'}}>
                    <Checkbox onChange={this.onIsAnonymity.bind(this)} checked={this.state.isAnonymity}>匿名评论</Checkbox>
                    <Button onClick={this.btnSubmitComment.bind(this)}>提交评论</Button>
                  </div>
                </div>
              </div>
          </div>
          <Sidebar ref="sidebar" />
          <BackTop/>
          <footer className="footer-4">
            <div className="divWidth">
              <div className="divTitle">
                <div className="divAbout">购物指南</div>
                <div className="divAbout" style={{marginLeft: '122px'}}>美丽阅读</div>
                <div className="divAbout" style={{marginLeft: '94px'}}>产品概览</div>
                <div className="divAbout" style={{marginLeft: '107px'}}>关于我们</div>
              </div>

              <div className="divMiddle">
                <a href="/index">
                  <img src="/src/styles/images/frobalogo.png" />
                </a>
                <ul>
                  <li><a href="javascript:void(0)">成为会员</a></li>
                  <li><a href="javascript:void(0)">我的账户</a></li>
                  <li><a href="javascript:void(0)">正品保障</a></li>
                  <li><a href="javascript:void(0)">订购服务</a></li>
                  <li><a href="javascript:void(0)">国际配送</a></li>
                  <li><a href="javascript:void(0)">帮助中心点</a></li>
                  <li><a href="javascript:void(0)">特别通告</a></li>
                </ul>
                <ul>
                  <li><a href="javascript:void(0)">阅读邮件</a></li>
                  <li><a href="javascript:void(0)">Facebook</a></li>
                  <li><a href="javascript:void(0)">YouTube</a></li>
                  <li><a href="javascript:void(0)">Instagram</a></li>
                </ul>
                <ul>
                  <li><a href="javascript:void(0)">推荐产品</a></li>
                  <li><a href="javascript:void(0)">女孩护肤</a></li>
                  <li><a href="javascript:void(0)">面膜</a></li>
                  <li><a href="javascript:void(0)">彩妆/口红</a></li>
                  <li><a href="javascript:void(0)">个人护肤</a></li>
                  <li><a href="javascript:void(0)">保健产品</a></li>
                </ul>
                <ul style={{marginRight: '0px'}}>
                  <li><a href="javascript:void(0)">关于 Froba 畐尔巴</a></li>
                  <li><a href="javascript:void(0)">联络我们</a></li>
                  <li><a href="javascript:void(0)">商务合作</a></li>
                  <li><a href="javascript:void(0)">网站地图</a></li>
                </ul>
              </div>
              <div className="divDeliveryPartner">
                <div className="divTitle1">购物网配送方式 Delivery Partner</div>
                <div>
                  <img src="/src/styles/images/about/poslaju.png" />
                  <img src="/src/styles/images/about/gdex.png" />
                  <img src="/src/styles/images/about/skynet.png" />
                  <img src="/src/styles/images/about/abx-express.png" />
                  <img src="/src/styles/images/about/frobagroup-delivery.png" />
                </div>
                <div className="divFloatRight" style={{marginRight: '16px'}}>
                  <img src="/src/styles/images/about/wotrus.png" />
                  <img src="/src/styles/images/about/ssl-secure.png" />
                  <img src="/src/styles/images/about/ssl-secure-transaction.png" />
                </div>
              </div>

              <div className="divDeliveryPartner">
                <div className="divTitle1">购物网付款方式 Payment Support</div>
                <div>
                  <img src="/src/styles/images/about/visa-straight-32px.png" />
                  <img src="/src/styles/images/about/paypal-straight-32px.png" />
                  <img src="/src/styles/images/about/maestro-straight-32px.png" />
                  <img src="/src/styles/images/about/mastercard-straight-32px.png" />
                  <img src="/src/styles/images/about/american-express-straight-32px.png" />

                  <img src="/src/styles/images/about/maybank.png" />
                  <img src="/src/styles/images/about/cimb-bank.png" />
                  <img src="/src/styles/images/about/american-express-straight-32px.png" />
                </div>
                <div className="divFloatRight" style={{marginTop: '-61px'}}>
                  <div className="divTitle1">官方社群 Stay Connected</div>
                  <p className="social">
                    <i className="fa fa-facebook"></i>
                    <i className="fa fa-twitter"></i>
                    <i className="fa fa-google"></i>
                    <i className="fa fa-instagram"></i>
                    <i className="fa fa-pinterest"></i>
                    <i className="fa fa-tumblr"></i>
                  </p>
                </div>
              </div>
              <div className="divCenter">
                <span style={{marginRight: '8px'}}>2017 Copyright Frobagroup.com. All Rights Reserved. 版权所有</span>
                <span className="spanBlod">Terms & Conditions  Privacy Policy  Cookie Statement</span>
              </div>
            </div>
          </footer>
        </div>
      )
    }
}
